package com.idanchuang.component.core.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public static <T> T getBean(Class<T> tClass) {
        checkState();
        return applicationContext.getBean(tClass);
    }

    public static <T> T getBean(String beanName) {
        checkState();
        return (T)applicationContext.getBean(beanName);
    }

    public static <T> T getBean(String beanName, Class<T> requiredType) {
        checkState();
        return applicationContext.getBean(beanName, requiredType);
    }

    private static void checkState() {
        if (SpringUtil.applicationContext == null) {
            throw new IllegalStateException("SpringUtil applicationContext is unready");
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtil.applicationContext = applicationContext;
    }
}
